import 'package:flutter/material.dart';
import 'package:sprintf/sprintf.dart'; //这个是一个拼接字符串的flutter库，主要是为了使用方便，你可以选择不使用，这样的话你需要自己拼接图片路径

//LYImagesAnimation(w: 100, h: 100, entry: ImagesAnimationEntry(1, 7, "")),

class LYImagesAnimationController {
  AnimationController? controller;
  void startPlay() {
    if (controller != null) {
      controller!.repeat();
    }
  }

  void stop() {
    if (controller != null) {
      controller!.stop();
    }
  }
}

class LYImagesAnimation extends StatefulWidget {
  final double w;
  final double h;
  final ImagesAnimationEntry entry;
  final int durationSeconds;
  final LYImagesAnimationController controller;
  const LYImagesAnimation(
      {super.key,
      this.w = 80,
      this.h = 80,
      required this.controller,
      required this.entry,
      this.durationSeconds = 2});

  @override
  State<LYImagesAnimation> createState() => _LYImagesAnimationState();
}

class _LYImagesAnimationState extends State<LYImagesAnimation>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<int> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
        vsync: this, duration: Duration(seconds: widget.durationSeconds));
    _animation =
        IntTween(begin: widget.entry.lowIndex, end: widget.entry.highIndex)
            .animate(_controller);
    widget.controller.controller = _controller;
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (ctx, child) {
        String frame = _animation.value.toString();
        debugPrint("=================${sprintf(widget.entry.basePath, [
              frame
            ])}=============");
        return Image.asset(
          sprintf(widget.entry.basePath, [frame]), //根据传进来的参数拼接路径
          gaplessPlayback: true, //避免图片闪烁
          width: widget.w,
          height: widget.h,
        );
      },
    );
  }
}

class ImagesAnimationEntry {
  int lowIndex = 0;
  int highIndex = 0;
  String basePath;

  ImagesAnimationEntry(this.lowIndex, this.highIndex, this.basePath);
}
